var router = require('koa-router')();
const fs = require('fs');// 引入文件读写模块
const filepath = '../learn-koa/data/data.json';// 指定文件路径.这里要注意下路径,可以看下报错
const jwt = require('jsonwebtoken');
const secret = 'learKoaToken';

router.prefix('/users');

router.post('/testToken',function * (next) {
  const _this = this;
  const token = this.header.token;
  jwt.verify(token,secret,(err,decode)=>{
    if(err){
        console.log(err)
    }else{
      _this.body=decode;
    }
})
});



router.post('/login', function* (next) {
  // 获取用户数据
  const _this = this;
  const requestData = this.request.body;
  if (requestData.username === 'admin' && requestData.password === '123456') {
    // 登录成功后，通过用户名和密码查询到用户id
    let id =  getUserId('admin','123456');
    const token = jwt.sign({id},secret,{expiresIn:'24h'});
    _this.body = {
      message:'获取 token 成功',
      code:1,
      token
    }
    
  }else{
    _this.body = '登录失败！'
  }
})

router.post('/addUser',function *(next){
  // 获取用户数据
  const _this = this;
  const requestData = this.request.body;// 拿到请求的数据
  
  fs.readFile(filepath, 'utf-8', (err, data) => {// data 是从文件中读取到的数据
    if(err){
        console.log(err);
        console.log('ERROR!Failed to read file!')
    }

    const params = data && JSON.parse(data) || [];// 拿到文件中原来存在的数据
    const id = params.length + 1;// 设置 id 从 1 开始，依次递增
    const newParams = [...params, { id, ...requestData }];
    fs.writeFile(filepath,JSON.stringify(newParams),(err)=>{
      if(err) _this.body = '写入文件失败！';
    })
})
})


const getUserId = function (username,password){
    const data = fs.readFileSync(filepath, 'utf-8');
    const params = data && JSON.parse(data) || [];// 拿到文件中原来存在的数据
    let id = null;
    params.forEach(item=>{
      if(item.username === username && item.password === password){
        id = item.id;
      }
    })
    return id;
}



module.exports = router;
